package org.dizem.minichat.service;

import org.apache.log4j.Logger;
import org.dizem.minichat.model.Client;
import org.dizem.minichat.util.VOUtil;
import org.dizem.minichat.vo.DataPacket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * User: DIZEM
 * Time: 11-3-26 上午9:40
 */
public class ClientMonitor extends Thread {

	private static Logger log = Logger.getLogger(ClientMonitor.class);

	private static int CLIENT_PORT = 3456;
	private Client client;
	private static boolean isReady = true;

	public ClientMonitor(Client client) {
		this.client = client;
	}

	@Override
	public void run() {
		try {
			DatagramSocket ds = createSocket();
			isReady = true;
			while (true) {
				log.info("Client Monitor is listening at port:" + CLIENT_PORT);

				byte[] data = new byte[10000];
				DatagramPacket packet = new DatagramPacket(data, data.length);
				ds.receive(packet);
				String s = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
				log.info("Received: " + s);

				DataPacket dp = (DataPacket) VOUtil.convertString2VO(s, DataPacket.class);
				work(dp);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private void work(DataPacket dp) {
		switch (dp.getOperation()) {

			case RESPONSE:
				break;
			case REGISTER:
				break;
			case LOGIN:
				break;
			case RECEIVED_SUCCESS:
				break;
		}
	}

	public static boolean isReady() {
		return isReady;
	}

	//	private void send(DataPacket dp) {
//		try {
//			DatagramSocket ds = new DatagramSocket();
//			String message = VOUtil.convertVOTo2String(dp);
//
//			byte[] data = message.getBytes("UTF-8");
//			DatagramPacket packet = new DatagramPacket(
//					data, data.length, InetAddress.getByName(serverAddress), serverPort
//			);
//			ds.send(packet);
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	private DatagramSocket createSocket() {
		try {
			DatagramSocket ds = new DatagramSocket(CLIENT_PORT);
			log.info("ClientMonitor start at port:" + CLIENT_PORT);
			return ds;

		} catch (SocketException e) {
			log.info("Port:" + CLIENT_PORT + " has already been used");

			CLIENT_PORT++;
			return createSocket();
		}
	}
}
